package com.qdlc.p2p.biz.protocol;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.BondCollectionService;
import com.qdlc.p2p.biz.service.BondService;
import com.qdlc.p2p.biz.service.BondTenderService;
import com.qdlc.p2p.biz.service.BorrowService;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.VerifyLogService;
import com.qdlc.p2p.biz.util.itext.PdfHelper;
import com.qdlc.p2p.common.constant.BorrowType;
import com.qdlc.p2p.common.exception.BorrowException;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.NumberUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.BorrowTender;
import com.qdlc.p2p.dal.dto.Protocol;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.BondCollectionModel;
import com.qdlc.p2p.dal.model.BondModel;
import com.qdlc.p2p.dal.model.BondTenderModel;
import com.qdlc.p2p.dal.model.BorrowModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

/**
 * 债权出让人下载协议实现类
 * 
 * @author wzh
 * @version 2.0
 * @since 2014-12-31
 */
@Service
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BondSellProtocol extends AbstractProtocolBean {
	
	private static Logger logger = Logger.getLogger(BondSellProtocol.class);
	
	protected BondService bondService;
	protected BondTenderService bondTenderService;
	protected BorrowTenderService borrowTenderService;
	protected VerifyLogService verifyLogService;
	protected BondCollectionService bondCollectionService;
	/**
	 * 债权标model
	 */
	protected BondModel bond;
	/**
	 * 债权人
	 */
	protected User bondUser;
	/**
	 * 购买人
	 */
	protected User buyUser;
	/**
	 * 购买债权记录
	 */
	protected List<BondTenderModel> tender;
	/**
	 * 债权转让人还款计划
	 */
	protected List<BondCollectionModel> collection;
	/**
	 * 原始投资记录
	 */
	protected BorrowTender borrowTender;
	 /**
     * 原始借款标审核时间
     */
	protected String vetifyTime;
	/**
	 * 原始借款标借款到期日
	 */
	protected String expirationDate;
	/**
	 * 债权购买人应收本息总和
	 */
	protected double bondCollectionAccountSum;
	/**
	 * 债权购买人应收本金总和
	 */
	protected double bondCollectionCapitalSum;
	/**
	 * 债权购买人应收利息总和
	 */
	protected double bondCollectionInterestSum;
	
	@Override
	public void validDownload() {
		// 判断是否有模板
		if (this.protocol == null || StringUtil.isBlank(this.protocol.getContent())) {
			throw new BorrowException("读取协议模板出错！");
		}
	}
	
	/**
	 * 业务核心处理方法
	 */
	@Override
	public void executer(long bondId, long bondTenderId, Protocol protocol, long userId) {
		// 初始化基础参数
		logger.info("初始化ProtocolBean");
		this.bondService = (BondService) BeanUtil.getBean("bondService");
		this.bondTenderService = (BondTenderService) BeanUtil.getBean("bondTenderService");
		this.borrowService = (BorrowService) BeanUtil.getBean("borrowService");
		this.borrowTenderService = (BorrowTenderService) BeanUtil.getBean("borrowTenderService");
		this.verifyLogService = (VerifyLogService) BeanUtil.getBean("verifyLogService");
		this.bondCollectionService = (BondCollectionService) BeanUtil.getBean("bondCollectionService");
		
		//获得bondModel对象
		this.bond = bondService.getBondModelByBondId(bondId);
		this.bondUser = bond.getUser();//债权人
		
		//获得borrowModel对象
		this.borrow = BorrowModel.instance(borrowService.getBorrowById(bond.getBorrowId()));
		
		String contextPath = ServletActionContext.getServletContext().getRealPath("/data/protocol/");
		this.downloadFileName = bond.getUuid() + ".pdf";
		this.inPdfName = contextPath + bondId + "_" + System.currentTimeMillis() + ".pdf";
		this.pdf = PdfHelper.instance(inPdfName);
		this.protocol = protocol;
		this.userId = userId;
		//投资记录
		this.tender = bondTenderService.getTenderListByBond(bond);
		this.collection = bondCollectionService.getCollectionModelListByBondId(bond.getId());
		Object[] obj = bondCollectionService.getSumBondCollectionByBondId(bondId);
		if(obj != null){
			this.bondCollectionAccountSum = NumberUtil.getDouble(obj[0].toString());
			this.bondCollectionCapitalSum = NumberUtil.getDouble(obj[1].toString());
			this.bondCollectionInterestSum = NumberUtil.getDouble(obj[2].toString());
		}
		//原始投资记录
		this.borrowTender = borrowTenderService.getTenderById(bond.getBorrowTenderId());
		Date fullTime = verifyLogService.findByType(bond.getBorrowId(), "borrow", 2).getTime();
		this.vetifyTime = DateUtil.dateStr6(fullTime);
		if(borrow.getType() == BorrowType.TYPE_SECOND){
			this.expirationDate = vetifyTime;
		}else{
			if(borrow.getBorrowTimeType() == 1){//天标
				this.expirationDate = DateUtil.dateStr6(DateUtil.rollDay(fullTime, borrow.getTimeLimit()));
				this.intervalDays = DateUtil.daysBetween(DateUtil.rollDay(fullTime, borrow.getTimeLimit()), fullTime);
			}else{
				this.expirationDate = DateUtil.dateStr6(DateUtil.rollMon(fullTime, borrow.getTimeLimit()));
				this.intervalDays = DateUtil.daysBetween(DateUtil.rollMon(fullTime, borrow.getTimeLimit()), fullTime);
			}
		}
		// 业务预处理
		prepare();
		// 下载协议校验
		validDownload();
		// 初始化参数
		initData();
		// 创建pdf逻辑
		createPdf();
	}	
	

	@Override
	public void prepare() {
	}
	
	@Override
	public void initData() {
		data.put("web_name", SystemConfigs.WEB_NAME);
		data.put("web_url", SystemConfigHelper.getValue(Nid.WEB_URL));
		data.put("bond", bond);
		data.put("borrow", borrow);
		data.put("bondUser", bondUser);
		data.put("tender", tender);
		data.put("collection", collection);
		data.put("buyUser", buyUser);
		data.put("borrowTender", borrowTender);
		data.put("nowDate", DateUtil.dateStr5(new Date()));
		data.put("vetifyTime", vetifyTime); //添加审核时间
		data.put("expirationDate", expirationDate);
		data.put("bondCollectionAccountSum", bondCollectionAccountSum);
		data.put("bondCollectionCapitalSum", bondCollectionCapitalSum);
		data.put("bondCollectionInterestSum", bondCollectionInterestSum);
	}
	
}
